// pages/listen/listen.js 
// 录音管理器
const recorderManager = wx.getRecorderManager();
// 播放器
const innerAudioContext = wx.createInnerAudioContext();
const app = getApp();
var router = require("../../router.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    start:'开始',
    list: [
      { title: '章鱼先生', data: '2018/06/19', pic: '/images/diary_tu.png', name: '辟谷百科辟谷百科辟谷百科', motton: '辟谷即不食五谷杂粮，是通过吸收自然精华之气，而进行减肥，排毒，养生的系统养生方法。这一做法起源较流行减肥，排毒，养生的系统养生方法。这一做法起源较流行减肥，排毒，养生的系统养生方法。这一做法起源较流减肥，排毒，养生的系统养生方法。这一做法起源较流减肥，排毒，养生的系统养生方法。这一做法起源较流行减行…', src: 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46', name: '此时此刻', author: '许巍', poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000' },
      
    ],
    xphoto: '/images/upload.png',
    yinpin: '',
    pictrueTempPath: "", // 临时途径
    soundRecording: {
      tempPath: "",
      duration: "",
      isPlay: false,// 临时录音
      play: true,

    },
    isnum: 3,
    
  },
  //上传图片
  xphotos: function () {
    var that = this;
    var xphoto = that.data.xphoto;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          xphoto: res.tempFilePaths
        });
      }
    })
  },
  /**
   * 录音开始
   */
  soundRecordingStart: function () {  
    var i = this.data.start;
    var st;
    if (i == '开始'){
      st = "开始录音"
    } 
    this.setData({
      start: st
    })
    const options = {
      duration: 600000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    }
    recorderManager.start(options);
  },
  /**
   * 录音完成
   */
  soundRecordingEnd: function () {
    var i = this.data.start;
    var st;
    if (i == '开始录音') {
      st = "录音结束"
    } else {
      st = "开始录音"
    }
    this.setData({
      start: st
    })
    let _this = this;
    recorderManager.stop();
    recorderManager.onStop(function (res) {
      let _tempPath = res.tempFilePath;
      let _duration = Math.ceil(res.duration / 1000);
      innerAudioContext.src = _tempPath;
      var miao = 540 * (_duration / 600)
      if (miao < 120){
        miao = 120
      }
      if (_duration > 60){    //大于60秒转化成分保留两位小数
        _duration = (_duration / 60).toFixed(2)
      }
      _this.setData({
        soundRecording: {
          tempPath: _tempPath,
          duration: _duration,
          isPlay: false,
          play: false
        },
       width: miao+'rpx'
    });
    var tempPath = _this.data.soundRecording.tempPath
    if (tempPath) {    
      wx.uploadFile({
        url: router.msg.upload, 
        filePath: tempPath,
        name: 'file',
        success: function (res) {
          var result = JSON.parse(res.data);         
          if (result.status){           
            _this.setData({
              yinpin: result.path
            })
          }                   
        }
      })
    }
    });
  },
  /**
   * 录音播放
   */
  soundRecordingPlay: function () {
    let _this = this;
    let _paused = innerAudioContext.paused;
    let _soundRecording = _this.data.soundRecording;
    if (_paused) {      
      innerAudioContext.play();
      _soundRecording.isPlay = true;
      this.time();
      setTimeout(function () {        
        let _soundRecording = _this.data.soundRecording;
        _soundRecording.isPlay = false;

        _this.setData({
          soundRecording: _soundRecording
        });
      }, _soundRecording.duration * 1000)
    } else {     
      innerAudioContext.stop();
      _soundRecording.isPlay = false;
      clearInterval(_this.time());
      _this.setData({
        isnum: 3
      })
    }
    _this.setData({
      soundRecording: _soundRecording
    });
  },
  time: function () {
    var _this = this;
    setInterval(function () {
      if (_this.data.soundRecording.isPlay) {
        switch (_this.data.isnum) {
          case 1:
            _this.setData({
              isnum: 2,
            })
            break;
          case 2:
            _this.setData({
              isnum: 3,
            })
            break;
          case 3:
            _this.setData({
              isnum: 1,
            })
            break;
        }
      } else {
        _this.setData({
          isnum: 3,
        })
      }

    }, 500);
  },
  /**
   * 删除录音
   */
  soundRecordingRemove: function () {
    var i = this.data.start;
    var st;
    if (i == '录音结束') {
      st = "开始"
    }
    this.setData({
      start: st
    })
    let _this = this;
    innerAudioContext.stop();
    _this.setData({
      soundRecording: {
        tempPath: "",
        duration: "",
        isPlay: false
      },
      yinpin: ""
    });
  },

  changeInputData: function (e) {
    var that = this;
    var inputId = e.currentTarget.id;
    var inputVlaue = e.detail.value;
    if (inputId == 'title') {
      that.setData({
        title: inputVlaue
      });
    } else {
      that.setData({
        content: inputVlaue
      });
    }
  },
  
  release: function () {
    var that    = this;
    var title   = that.data.title;
    var content = that.data.content;
    var yinpin  = that.data.yinpin;
    var duration = that.data.soundRecording.duration;      
    if (title && content && yinpin && duration) {
      app.request({
        url: router.msg.say,
        method: "POST",
        data: {
          msid: that.data.msid,
          uid: wx.getStorageSync('uid'),
          title: title,
          content: content,
          yinpin: yinpin,
          duration: duration,
        },
        success: function (data) {        
          if (data) {        
            wx.showToast({
              title: '发布成功',
              icon: 'none'
            });
            setTimeout(function () {            
              wx.reLaunch({
                url: '../list/list'
              })
            }, 1500);
          } else {
            wx.showToast({
              title: '发布失败,请重试',
              icon: 'none'
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '确保标题内容录音完成再进行此操作',
        duration: 2000,
        icon: 'none'
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    var that = this;
    this.setData({
      msid: options.id
    });
    app.request({
      url: router.msg.index,
      data: {
        id: options.id
      },
      success: function (data) {       
        if (data) {        
          var obj = {};
          obj.title = data.nickname
          obj.data = data.createtime
          obj.pic = data.head
          obj.name = data.title
          obj.motton = data.content
          obj.id = data.msid
          that.data.list.push(obj);          
          that.setData({
            list: that.data.list
          });
        }
      }
    })
  },
  //分享
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      var that = this;
      // 来自页面内转发按钮    
      var id = res.target.dataset.id;
      var index = res.target.dataset.ctr;
      var title = that.data.list[index].name;
      return {
        title: title,
        path: '/pages/list/list',
        success: function (res) {
          app.request({
            url: router.msg.share,
            method: "POST",
            data: {
              id: id,
            },
            success: function (data) {
              if (data) {
                var list = that.data.list;
                var share = list[index].share;
                list[index].share = share + 1;
                that.setData({
                  list: list
                })
                wx.showToast({
                  title: '分享成功',
                  icon: 'success',
                  duration: 2000
                });
              } else {
                wx.showToast({
                  title: '分享失败请重试',
                  icon: 'none',
                  duration: 2000
                });
              }
            }
          });
        },
        fail: function (res) {
          wx.showToast({
            title: '分享已取消',
            icon: 'none',
            duration: 2000
          });
        }
      }
    }
  },
})